<template lang="">
  <div>
    <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="loginname"
          label="用户名"
          placeholder="用户名"
          :rules="[
            {
              pattern: /^[a-zA-Z]\w{4,}$/,
              message: '用户只能以字母开头，以数字字母下滑线组合，至少5位'
            }
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ pattern: /^\S{5,}$/, message: '至少5位' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
    <van-button round type="success" @click="regHanlder" class="btn">注册</van-button>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
let router = useRouter()
import { showSuccessToast, showFailToast } from 'vant';


import { useUser } from '@/stores/user'
let user = useUser()

import { login } from '@/api/user'

const username = ref('')
const password = ref('')
function onSubmit(values: any) {
  login(values).then((r) => {
    if (r.code == '200') {
      showSuccessToast(r.data.message);

      user.loginname = username.value
      user.token = r.data.token
      user.userid = r.data.userid
      router.push('/layout')
    }else{
      showFailToast(r.data.message);
    }
  })
}

function onClickLeft() {
  router.back()
}

function regHanlder() {
  router.push('/reg')
}
</script>
<style lang="css" scoped>
.van-form {
  margin-top: 20vh;
}
.btn {
  width: 92vw;
  margin-left: 4vw;
}
</style>
